package com.jams.goodox.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.hangzhou.jin.customview.Title;
import com.jams.goodox.BasePayActivity;
import com.jams.goodox.R;
import com.jams.goodox.TownApplicationLike;
import com.jams.goodox.activity.home.HomeActivity;
import com.jams.goodox.activity.serve.meet.MeetRoomListActivity;
import com.jams.goodox.activity.serve.park.ParkingApplyActivity;
import com.jams.goodox.activity.wallet.MineWalletActivity;
import com.jams.goodox.activity.wallet.PayConstants;
import com.jams.goodox.activity.wallet.PaySuccessActivity;
import com.jams.goodox.constant.Constants;
import com.jams.goodox.constant.UamaPayCode;
import com.jams.goodox.entity.PayInfo;
import com.jams.goodox.entity.StringBean;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.pay.AiliPayBean;
import com.jams.goodox.entity.pay.BalancePayBean;
import com.jams.goodox.entity.pay.WeChatPayBean;
import com.jams.goodox.listen.PayListener;
import com.jams.goodox.listen.SuccessListener;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.MineService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.MessageDialog;
import com.jams.goodox.utils.MoneyUtils;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.TipAlertDialog;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.LRTextView;
import com.jams.goodox.widget.XProgressDialog;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * Created by jams on 2017/7/28
 * ***
 * Tel: ***
 * Desc:支付方式选择页面
 */
public class ChoosePayActivity extends BasePayActivity {

    @Bind(R.id.lr_choose_pay_order_id)
    LRTextView lrChoosePayOrderId;
    @Bind(R.id.lr_choose_pay_order_server)
    LRTextView lrChoosePayOrderServer;
    @Bind(R.id.lr_choose_pay_order_total_money)
    LRTextView lrChoosePayOrderTotalMoney;
    @Bind(R.id.lr_choose_pay_order_real_money)
    LRTextView lrChoosePayOrderRealMoney;
    @Bind(R.id.red_packet)
    TextView redPacket;
    @Bind(R.id.red_packet_layout)
    RelativeLayout redPacketLayout;
    @Bind(R.id.discount)
    TextView discount;
    @Bind(R.id.discount_layout)
    RelativeLayout discountLayout;
    @Bind(R.id.rcv_pay_way)
    RecyclerView rcvPayWay;
    @Bind(R.id.discount_red_layout)
    LinearLayout discountRedLayout;
    @Bind(R.id.pay_btn_balance_check)
    ImageView payBtnBalanceCheck;
    @Bind(R.id.balance)
    TextView tvBalance;


    private PayInfo payInfo;
    private double balance; //余额
    private String userId;//企业账户id(企业订单需要传）
    private boolean isFirstInitSelect = true; // 只在页面第一次加载的时候去主动设置按钮选中状态
    private int selectPayType = -1;//选择的支付方式
    private RecycleCommonAdapter adapter;
    private final int ComeOther = 0;// 来源是其他不需要处理回退的页面
    private int come;// 从哪个页面跳转过来的

    @Override
    protected int getLayoutId() {
        return R.layout.activity_choose_pay;
    }

    @Override
    protected void init() {
        super.init();
        setTitleVisibility(false);
        Title.init("稍后付款", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doBackThing();
            }
        }, this, "选择支付方式");
        come = getIntent().getIntExtra("come", ComeOther);
        payInfo = (PayInfo) getIntent().getSerializableExtra("payInfo");//必传字段
        if (payInfo == null) return;
        userId = payInfo.getOrderCreateClassfiy() == 2 ? DataCacheManager.getInstance().getUser().getEnterpriseAdminId() : null;//如果是个人订单则不需要userId
        setData();
    }

    private void setData() {
        //设置订单编号
        lrChoosePayOrderId.setTvRight(payInfo.getOrderCode());
        //设置服务名称
        lrChoosePayOrderServer.setTvRight(payInfo.getServerName());
        //设置合计金额
        lrChoosePayOrderTotalMoney.setTvRight(MoneyUtils.withSpaceMoney(payInfo.getOrderAllMoney()));
        //设置应付金额
        lrChoosePayOrderRealMoney.setTvRight(MoneyUtils.withSpaceMoney(payInfo.getOrderMoney()));
        //如果红包金额为0，隐藏红包区域
        if (payInfo.getRedPacketMoney() > 0) {
            redPacketLayout.setVisibility(View.VISIBLE);
            redPacket.setText(MoneyUtils.withSpaceMoney(payInfo.getRedPacketMoney()));
        } else {
            redPacketLayout.setVisibility(View.GONE);
        }

        //如果折扣为10时，隐藏折扣区域
        if (payInfo.getOnlinePayDiscount() == 10) {
            discountLayout.setVisibility(View.GONE);
        } else {
            discountLayout.setVisibility(View.VISIBLE);
            discount.setText(String.valueOf(payInfo.getOnlinePayDiscount() + "折"));
        }
        // 只有2个layout都不在的时候 整个布局就隐藏
        discountRedLayout.setVisibility(payInfo.getOnlinePayDiscount() == 10 && payInfo.getRedPacketMoney() <= 0 ? View.GONE : View.VISIBLE);
        rcvPayWay.setLayoutManager(new LinearLayoutManager(this));
        if (CollectionUtils.hasData(payInfo.getPayType())) {
            adapter = new RecycleCommonAdapter<Integer>(this, payInfo.getPayType(), R.layout.pay_way_item) {
                @Override
                public void convert(RecycleCommonViewHolder helper, final Integer item, int position) {
                    switch (item) {
                        case UamaPayCode.PayType.Type_Aili://支付宝
                            helper.getView(R.id.iv_pay_icon).setBackgroundResource(R.mipmap.order_pay_zfb);
                            helper.setText(R.id.tv_pay_name, "支付宝支付");
                            helper.setText(R.id.tv_pay_desc, "推荐有支付宝账户的用户使用");
                            break;
                        case UamaPayCode.PayType.Type_WeChat://微信
                            helper.getView(R.id.iv_pay_icon).setBackgroundResource(R.mipmap.order_pay_wx);
                            helper.setText(R.id.tv_pay_name, "微信支付");
                            helper.setText(R.id.tv_pay_desc, "推荐安装微信5.0及以上版本的用户");
                            break;
                    }
                    //如果选择的是当前支付方式，则勾选，否则清除勾选
                    helper.getView(R.id.pay_check).setBackgroundResource(selectPayType == item ? R.mipmap.check_price_icon : R.mipmap.pay_choose);
                    helper.setOnItemClickListener(new OnRecycleItemClickListener() {
                        @Override
                        public void itemClick() {
                            if (selectPayType == item) {
                                selectPayType = -1;
                            } else {
                                selectPayType = item;
                            }
                            setBalanceCheckStatus(false);
                        }
                    });
                }
            };
            rcvPayWay.setAdapter(adapter);
        }
    }

    /**
     * 请求最新余额数据
     */
    public void requestBalance() {
        enqueue(createCallService(MineService.class).balance(userId), new RetrofitCallbackListener<StringBean>() {
            @Override
            public void onSuccess(Call<StringBean> call, StringBean result) {
                try {
                    balance = Double.parseDouble(result.getData());
                } catch (NumberFormatException e) {
                    balance = 0.00;
                }
                tvBalance.setText(User.getPriceStyle(balance, ""));
                // 初始化支付按钮选中项
                initSelected();
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    //初始化支付选择
    private void initSelected() {
        if (isFirstInitSelect) {
            isFirstInitSelect = false;
            if (balance >= payInfo.getOrderMoney()) {
                // 余额大于等于订单实付金额
                selectPayType = UamaPayCode.PayType.Type_Balance;
                setBalanceCheckStatus(true);
            } else {
                if (CollectionUtils.hasData(payInfo.getPayType())) {
                    //当应付金额大余额，直接选择第一个第三方支付方式
                    selectPayType = payInfo.getPayType().get(0);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    @OnClick({R.id.confirm_pay, R.id.pay_btn_balance})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.confirm_pay:
                pay();
                break;
            case R.id.pay_btn_balance:
                if (!checkBalanceIsValid()) {
                    return;
                }
                if (selectPayType == UamaPayCode.PayType.Type_Balance) {
                    setBalanceCheckStatus(false);
                    selectPayType = -1;
                } else {
                    selectPayType = UamaPayCode.PayType.Type_Balance;
                    setBalanceCheckStatus(true);
                }
                break;
        }
    }

    //支付
    private void pay() {
        if (selectPayType == -1) {
            ToastUtil.show(TownApplicationLike.getInstance(), "请选择支付方式");
        }
        switch (selectPayType) {
            case UamaPayCode.PayType.Type_Balance://余额支付
                if (!checkBalanceIsValid()) {
                    return;
                }
                BalancePayBean balancePayBean = new BalancePayBean();
                balancePayBean.setUserId(userId);
                balancePayBean.setType(payInfo.getOrderCreateClassfiy());
                balancePayBean.setBalance(StringUtils.doubleToString(balance));
                balancePayBean.setOrderId(payInfo.getOrderId());
                String paySubCode = (payInfo.getPaySubCode() == 0) ? null : String.valueOf(payInfo.getPaySubCode());//此处仅当是是场地or停车服务，subCode不为空
                balancePayBean.setPaySubCode(paySubCode);
                payByBalance(balancePayBean, new PayListener() {
                    @Override
                    public void payResult(int status, String msg) {
                        switch (status) {
                            case UamaPayCode.PAY_SUCCESS:
                                paySuccess();
                                break;
                            case UamaPayCode.BALANCE_CHANGE:
                                TipAlertDialog.showTip(ChoosePayActivity.this, null, msg, new SuccessListener() {
                                    @Override
                                    public void success() {
                                        requestBalance();
                                    }
                                });
                                break;
                            case UamaPayCode.PAY_ERROR:
                                showPayExceptionDialog("提示", msg);
                                break;
                        }
                    }
                });
                break;

            case UamaPayCode.PayType.Type_Aili://支付宝支付
                AiliPayBean ailiPayBean = new AiliPayBean();
                ailiPayBean.setId(payInfo.getOrderId());
                ailiPayBean.setCode(payInfo.getOrderCode());
                ailiPayBean.setType(payInfo.getThirdPayConfigType());
                ailiPayBean.setMoneyCharge(StringUtils.doubleToString(payInfo.getOrderMoney()));
                ailiPayBean.setTitle("支付");
                payByAili(ailiPayBean, new PayListener() {
                    @Override
                    public void payResult(int status, String msg) {
                        switch (status) {
                            case UamaPayCode.PAY_SUCCESS:
                                queryPayStatusRequest(false);
                                break;
                        }
                    }
                });
                break;
            case UamaPayCode.PayType.Type_WeChat:
                WeChatPayBean weChatPayBean = new WeChatPayBean();
                weChatPayBean.setOrderId(payInfo.getOrderId());
                weChatPayBean.setPayType(payInfo.getThirdPayConfigType());
                payByWeChat(weChatPayBean, new PayListener() {
                    @Override
                    public void payResult(int status, String msg) {
                        switch (status) {
                            case UamaPayCode.PAY_SUCCESS:
                                queryPayStatusRequest(false);
                                break;
                        }
                    }
                });
                break;
        }
    }

    //设置余额支付选中状态
    private void setBalanceCheckStatus(boolean bool) {
        if (bool) {
            payBtnBalanceCheck.setBackgroundResource(R.mipmap.check_price_icon);
        } else {
            payBtnBalanceCheck.setBackgroundResource(R.mipmap.pay_choose);
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 支付成功处理
     */
    public void paySuccess() {
        Intent intent = new Intent(mContext, PaySuccessActivity.class);
        intent.putExtra("type", payInfo.getOrderCreateClassfiy());
        intent.putExtra("payMoney", payInfo.getOrderMoney());
        intent.putExtra("paySubCode", payInfo.getPaySubCode());
        startActivity(intent);
        this.finish();
    }

    /**
     * 没有足够余额支付的弹窗
     */
    private void noEnoughBalanceDialog() {
        String noEnoughBalance;
        if (!isUserOrder()) {//企业
            noEnoughBalance = getString(R.string.company_money_unenough);
        } else {
            noEnoughBalance = "您的账户余额不足，请选择其它支付方式";
        }
        new MaterialDialog.Builder(this).content(noEnoughBalance).positiveText("知道了").onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
            }
        }).show();
    }

    //检查余额支付
    private boolean checkBalanceIsValid() {
        //当金额为0时，提示
        if (balance == 0) {
            if (!isUserOrder()) {//企业支付
                new MaterialDialog.Builder(mContext).content("您的账户余额不足，请选择其他支付方式或去企业账号先充值再进行支付").positiveText("知道了")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        }).show();
            } else {
                // 提示去充值
                new MaterialDialog.Builder(mContext).content("您的钱包余额为0，请充值后再支付").positiveText("去充值")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                qStartActivity(MineWalletActivity.class);
                            }
                        }).negativeText("暂不充值").onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                }).show();
            }
            return false;
        }
        if (balance < payInfo.getOrderMoney()) {
            //余额小于应付金额
            noEnoughBalanceDialog();
            return false;
        }
        return true;
    }

    //判断是不是用户订单 1表示用户订单，2表示企业订单
    private boolean isUserOrder() {
        return payInfo.getOrderCreateClassfiy() == 1;
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestBalance();
    }

    /**
     * 支付异常dialog
     */
    public void showPayExceptionDialog(String title, String message) {
        if (payInfo == null) return;
        String negativeStr = "我的服务订单";
        if (payInfo.getOrderCreateClassfiy() == 2) {
            negativeStr = "企业服务订单";
        }

        switch (payInfo.getPaySubCode()) {
            case Constants.PARKING_CODE:
                negativeStr = "继续申请";
                break;
            case Constants.MEET_CODE:
                negativeStr = "继续申请";
                break;
        }
        new MaterialDialog.Builder(mContext).title(title).content(message).cancelable(false)
                .positiveText("回首页").onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                // 跳转首页
                Intent i = new Intent(ChoosePayActivity.this, HomeActivity.class);
                i.putExtra("first", true);
                startActivity(i);
                finish();
            }
        }).negativeText(negativeStr).onNegative(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                doFailureReturnOther();
            }
        }).show();
    }

    /**
     * 支付失败时，返回不同的页面（场地预定首页，停车申请首页，服务订单列表页）
     */
    private void doFailureReturnOther() {
        Intent intent = new Intent();
        if (payInfo.getPaySubCode() == Constants.PARKING_CODE) {
            intent.setClass(mContext, ParkingApplyActivity.class);
            intent.putExtra("paySuccess", true);
            startActivity(intent);
            finish();
            return;
        }
        if (payInfo.getPaySubCode() == Constants.MEET_CODE) {
            intent.setClass(mContext, MeetRoomListActivity.class);
            intent.putExtra("paySuccess", true);
            startActivity(intent);
            finish();
            return;
        }
        if (payInfo.getOrderCreateClassfiy() == 2) {//企业订单
            intent.setClass(mContext, HomeActivity.class);
            intent.putExtra(HomeActivity.MODE, 30);
            startActivity(intent);
        } else {
            intent.setClass(mContext, HomeActivity.class);
            intent.putExtra(HomeActivity.MODE, 27);
            startActivity(intent);
        }
        finish();
    }

    private XProgressDialog dialog;

    /**
     * 去后台检查支付是否成功 (多次调用为了满足3秒内知道后台是否处理完成)
     *
     * @param isEnd 是否是最后一次调用
     */
    private void queryPayStatusRequest(final boolean isEnd) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(!needQueryPayStatus()){//是否需要检查支付状态
                    ToastUtil.show(mContext, "支付成功");
                    paySuccess();
                    return;
                }
                if (dialog == null) {
                    dialog = new XProgressDialog(ChoosePayActivity.this, "支付确认中，请稍后…", XProgressDialog.THEME_CIRCLE_PROGRESS);
                    dialog.show();
                }
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        enqueue(createCallService(MineService.class).payStatus(payInfo.getOrderId(), PayConstants.ORDER), new RetrofitCallbackListener<StringBean>() {
                            @Override
                            public void onSuccess(Call<StringBean> call, StringBean result) {
                                if (dialog != null) {
                                    dialog.dismiss();
                                }

                                if (null != result && null != result.getData()) {
                                    if (TextUtils.equals(result.getData(), "1")) {  //成功
                                        ToastUtil.show(mContext, "支付成功");
                                        paySuccess();
                                    } else if (TextUtils.equals(result.getData(), "2")) {
                                        showPayExceptionDialog("订单支付确认中", "订单支付确认中，您可到我的服务订单中查看订单状态");
                                    } else {
                                        MessageDialog.showSingleConfirmDialog(mContext, "", "订单支付失败，您的账户可能存在多人操作，导致余额变动，请重新支付。",
                                                "确定", new MessageDialog.DialogConfirmClickListener() {
                                                    @Override
                                                    public void confirm() {
                                                        requestBalance();
                                                    }
                                                });
                                    }
                                }
                            }

                            @Override
                            public void onError(String msg) {
                                if (isEnd)
                                    dialog.dismiss();
                                else
                                    queryPayStatusRequest(true);
                            }
                        });
                    }
                }, 1200);
            }
        });
    }

    /**
     * 于此判断是否需要支付成功后查询支付状态（仅订单）
     * @return true 需要 false 不需要
     */
    private boolean needQueryPayStatus(){
       return Constants.PayType.Type_Order.equalsIgnoreCase(payInfo.getThirdPayConfigType());
    }

    @Override
    public void doBackThing() {
        if (come != ComeOther) {
            new MaterialDialog.Builder(mContext).content("确认稍后付款？下单后15分钟内未支付成功，订单将被关闭，请尽快完成支付！")
                    .positiveText("稍后付款").onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    qStartActivity(HomeActivity.class);
                }
            }).negativeText("继续付款").onNegative(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    dialog.dismiss();
                }
            }).show();
        } else {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        doBackThing();
    }

}
